package com.zzqstart.cateservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zzqstart.cateservice.entity.CateCategory;
import com.zzqstart.cateservice.service.CateCategoryService;
import com.zzqstart.commonutils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author testjava
 * @since 2023-03-06
 */
@RestController
@RequestMapping("/cateservice/catecategory")
public class CateCategoryController {

    @Autowired
    private CateCategoryService cateCategoryService;

    @PostMapping("/appendCategory")
    public R appendCategory(@RequestBody CateCategory category){
        boolean isSaveOrUpdate = cateCategoryService.saveOrUpdate(category);
        return R.ok().data("isSaveOrUpdate",isSaveOrUpdate);
    }

    @GetMapping("/getCatetoryById/{id}")
    public R getCatetoryById(@PathVariable String id){
        CateCategory category = cateCategoryService.getById(id);
        return R.ok().data("category",category);
    }

    @Transactional
    @DeleteMapping("/deleteCatetoryById/{id}")
    public R deleteCatetoryById(@PathVariable String id){
        CateCategory category = cateCategoryService.getById(id);
        String parentId = category.getParentId();

        boolean isRemove = false;
        if (!parentId.equals("0")){
            isRemove = cateCategoryService.removeById(id);
        }else {
            List<String> idList = cateCategoryService.getChildrenIdListById(id);
            cateCategoryService.removeByIds(idList);
            cateCategoryService.removeById(id);
        }
        return R.ok().data("isRemove",isRemove);
    }
}

